package com.example.fast.common.util;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Md5Utils
 */
@Slf4j
public class Md5Utils {

    private Md5Utils() {
    }

    private static final Object MD5_LOCK = new Object();
    private static MessageDigest md;

    static {
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error("获取MD5算法失败\n{}", e.getMessage());
        }
    }

    public static String encryptMd5(String encTxt, String salt) {
        return encryptMd5(encTxt + salt);
    }

    private static String encryptMd5(String encTxt) {
        StringBuilder builder;
        byte[] b;
        synchronized (MD5_LOCK) {
            md.update(encTxt.getBytes());
            b = md.digest();
        }
        builder = new StringBuilder(b.length * 2);
        for (byte aB : b) {
            if (((int) aB & 0xff) < 0x10) {
                builder.append("0");
            }
            builder.append(Long.toHexString((int) aB & 0xff));
        }
        return builder.toString();
    }

}
